import publicFun from '../../utils/publicFun.js';
const util = require('../../request/index')
const phoneRexp = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
Page({
  data: {
    btnTxt: '获取验证码',
    isGetCode: false,
    Loading: false,
    countDown: 60,
    formData: {
      userPhone: '',
      code: '',
      userId:  wx.getStorageSync('userInfo').userId
    }
  },
  onLoad(options) {

  },
  onShow: function () {

  },

  formSubmit(e) {
    let that = this,
      formData = e.detail.value,
      errMsg = '';
    that.setData({
      Loading: true
    })
    if (!formData.userPhone) {
      errMsg = '手机号不能为空！';
    }
    if (!formData.code) {
      errMsg = '验证码不能为空！';
    }
    if (!formData.userId) {
      errMsg = '账号不能为空！';
    }
    if (formData.userPhone) {
      if (!phoneRexp.test(formData.userPhone)) {
        errMsg = '手机号格式有误！';
      }
    }
    if (errMsg) {
      that.setData({
        Loading: false
      })
      publicFun._showToast(errMsg);
      return false
    }
    //连接服务器进行验证码手机号验证操作
    // 发送验证码请求
    util.request_json_post('/web/phone/binding-update', this.data.formData).then((res) => {
      if (res.code == 200) {
        wx.showToast({
          title: '更改绑定成功！',
          icon: 'none'
        })
        that.setData({
          Loading: false
        })
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'error'
        })
      }
    })
  },
  getPhoneCode() {
    let that = this,
      formData = that.data.formData,
      errMsg = '';
    errMsg = !formData.userPhone ? '手机号不能为空！' :
      formData.userPhone && !phoneRexp.test(formData.userPhone) ? '手机号格式有误！' :
      '';
    if (errMsg) {
      publicFun._showToast(errMsg);
      return false
    }
    util.request_post('/web/phone/code', {
      userPhone: this.data.formData.userPhone
    }).then((res) => {
      if (res.code == 200) {
        wx.showToast({
          title: '发送验证码成功！',
          icon: 'none'
        })
        that.timer();
        // 连接服务器进行获取验证码操作
        that.setData({
          isGetCode: true
        })
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    })



  },
  timer() { //验证码倒计时
    let that = this,
      countDown = that.data.countDown;
    let clock = setInterval(() => {
      countDown--
      if (countDown >= 0) {
        that.setData({
          countDown: countDown
        })
      } else {
        clearInterval(clock)
        that.setData({
          countDown: 60,
          isGetCode: false,
          btnTxt: '重新获取'
        })
      }
    }, 1000)
  },
  phoneInput(e) { //输入检索
    let that = this,
      formData = that.data.formData,
      inputType = e.currentTarget.dataset.id,
      inputValue = e.detail.value;
    inputType === 'userPhone' ?
      formData.userPhone = inputValue : formData.code = inputValue;
    that.setData({
      formData
    })
  }
})